#!/bin/sh

zero_enable="$(uci -q get zerotier.sample_config.enabled)"

[ "${zero_enable}" -eq "1" ] || exit 1

count=0
[ -f "/tmp/zero.log" ] && {
	while [ -z "$(ifconfig | grep 'zt' | awk '{print $1}')" ]
	do
		sleep 2
		let count++
		[ "${count}" -lt 5 ] || exit 19
	done
}

nat_enable="$(uci get zerotier.sample_config.nat)"
zt0="$(ifconfig | grep 'zt' | awk '{print $1}')"
echo "${zt0}" > "/tmp/zt.nif"

[ "${nat_enable}" -eq "1" ] && {
	for i in ${zt0}
	do
		ip_segment=""
		iptables -I FORWARD -i "$i" -j ACCEPT
		iptables -I FORWARD -o "$i" -j ACCEPT
		iptables -t nat -I POSTROUTING -o "$i" -j MASQUERADE
		ip_segment="$(ip route | grep "dev $i proto kernel" | awk '{print $1}')"
		iptables -t nat -I POSTROUTING -s "${ip_segment}" -j MASQUERADE
	done
}
